package com.zjw.handler.security;

import com.alibaba.fastjson.JSON;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理器
 *
 * @author LKZY
 * @date 2023/12/14 15:36
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException e)
            throws IOException, ServletException {
        System.out.println("------错误beg----a-↓");
        e.printStackTrace();
        ResponseResult res = null;
        if(e instanceof InsufficientAuthenticationException){
           res = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else if (e instanceof BadCredentialsException) {
            res = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }else {
            res = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
        }
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(res));

    }
}
